import { loginReq, logoutReq, getInfoReq, getMenuLanguage } from './api/user'
import { setToken, removeToken } from '@/utils/auth'
import { ObjTy } from '~/common'
import router, { constantRoutes, asyncRoutes } from '@/router'
import { defineStore } from 'pinia'
import { usePermissionStore } from '@/store/permission'
import { useTagsViewStore } from '@/store/tagsView'
import setting from '@/settings'
import { lang } from 'moment-mini'

const resetRouter = () => {
  const asyncRouterNameArr: Array<any> = asyncRoutes.map((mItem) => mItem.name)
  asyncRouterNameArr.forEach((name) => {
    if (router.hasRoute(name)) {
      router.removeRoute(name)
    }
  })
}

export const useUserStore = defineStore('user', {
  state: () => {
    return {
      id: 0,
      username: '',
      avatar: '',
      roles: [] as Array<any>,
      menu: <any>[],
      nickname: '',
      email: '',
      phone: '',
      language: '',
      timeZone: '',
      langDict: {}
    }
  },

  actions: {
    M_id(id: number) {
      this.$patch((state) => {
        state.id = id
      })
    },
    M_username(username: string) {
      this.$patch((state) => {
        state.username = username
      })
    },
    M_email(email: string) {
      this.$patch((state) => {
        state.email = email
      })
    },
    M_nickname(nickname: string) {
      this.$patch((state) => {
        state.nickname = nickname
      })
    },
    M_phone(phone: string) {
      this.$patch((state) => {
        state.phone = phone
      })
    },
    M_language(language: string) {
      this.$patch((state) => {
        state.language = language
      })
      setting.defaultLanguage = language
    },
    M_timeZone(timeZone: string) {
      this.$patch((state) => {
        state.timeZone = timeZone
      })
    },
    M_roles(roles: Array<string>) {
      this.$patch((state) => {
        state.roles = roles
      })
    },
    M_menu(menu: Array<any>) {
      this.$patch((state) => {
        state.menu = menu
      })
    },
    M_langDict(langDict: object) {
      this.$patch((state) => {
        state.langDict = langDict
      })
    },

    login(data: ObjTy) {
      return new Promise((resolve, reject) => {
        loginReq(data)
          .then((res: ObjTy) => {
            if (res.code === 20000) {
              //commit('SET_Token', res.data?.jwtToken)
              // console.log(res, 333)
              // setToken(res.data?.jwtToken)
              setToken(res.data)
              resolve(null)
            } else {
              reject(res)
            }
          })
          .catch((error: any) => {
            reject(error)
          })
      })
    },
    // get user info
    getInfo() {
      return new Promise((resolve, reject) => {
        getInfoReq()
          .then((response: any) => {
            const { data } = response
            if (!data) {
              return reject('Verification failed, please Login again.')
            }

            const currentLang = data.language
            const languageRelation = { zhCN: 'chineseSimplified', zhTW: 'chineseTaiwan', en: 'english' }

            const langDict = {}
            // 默认是中文内容 中文内容不做处理 且有用户要求的语言包
            if (currentLang !== 'zhCN' && languageRelation[currentLang]) {
              console.log('需要多语言')

              getMenuLanguage().then((languageInfo: any) => {
                const langInfo = languageInfo.data

                const targetLangInfo = langInfo[languageRelation[currentLang]]
                const chineseInfo = langInfo[languageRelation['zhCN']]
                for (let i = 0; i < targetLangInfo.length; i++) {
                  langDict[chineseInfo[i]] = targetLangInfo[i]
                }
                this.M_langDict(langDict)
              })
            }
            console.log(langDict)

            //此处模拟数据
            const { id, roles, username, menu, email, nickname, phone, language, timeZone, buttonList } = data

            const rolesArr: any = localStorage.getItem('roles')
            if (rolesArr) {
              data.roles = JSON.parse(rolesArr)
            } else {
              data.roles = ['admin']
              localStorage.setItem('roles', JSON.stringify(data.roles))
              localStorage.setItem('menu', JSON.stringify(data.menu))
            }
            this.M_id(id)
            this.M_username(username)
            this.M_roles(roles)
            this.M_menu(menu)
            this.M_nickname(nickname)
            this.M_email(email)
            this.M_phone(phone)
            this.M_language(language)

            sessionStorage.setItem('permission', JSON.stringify(buttonList))
            localStorage.setItem('language', language)
            this.M_timeZone(timeZone)
            resolve(data)
          })
          .catch((error: any) => {
            reject(error)
          })
      })
    },
    // user logout
    logout() {
      return new Promise((resolve, reject) => {
        logoutReq()
          .then(() => {
            this.resetState()
            resolve(null)
          })
          .catch((error: any) => {
            reject(error)
          })
      })
    },
    resetState() {
      return new Promise((resolve) => {
        this.M_username('')
        this.M_roles([])
        removeToken() // must remove  token  first
        resetRouter() // reset the router
        const permissionStore = usePermissionStore()
        permissionStore.M_isGetUserInfo(false)
        const tagsViewStore = useTagsViewStore()
        tagsViewStore.delAllViews()
        resolve(null)
      })
    }
  }
})
